package com.zzy.test.service;

import com.zzy.test.mapper.UserMapper;
import com.zzy.test.pojo.User;
import com.zzy.test.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author Lucas-zhang
 * @description TODO
 * @date 2022-03-20 11:09
 */
@Service
public class EmailCodeUserDetailsService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserMapper userMapper;

    public UserDetails loadUserByEmail(Authentication authentication)  {
        String email = authentication.getName();
        System.out.println("email = " + email);

        // 首先判断该用户是否存在
        User user = userMapper.findUserByEmail(email);
        if (user == null) {
            return null;
        }
        System.out.println("user = " + user);
        // 查找redis中邮箱号码为key对应的验证码value
        String emailCode = redisUtil.get(email).toString();

        // 获取用户提交的验证码
        String credentials = (String) authentication.getCredentials();
        if (!StringUtils.hasLength(credentials)) {
            return null;
        }
        // 验证码正确
        if (credentials.equalsIgnoreCase(emailCode)) {
            return user;
        }

        return null;
    }

}
